package com.fm.financemanage.service;

import com.fm.financemanage.component.QuartzComponent;
import com.fm.financemanage.component.TaskQuartzBean;
import com.fm.financemanage.exception.BusinessException;
import com.fm.financemanage.mapper.WxTemplemtMapper;
import com.fm.financemanage.model.po.WxTemplemt;
import com.fm.financemanage.model.vo.PageVo;
import com.fm.financemanage.utils.TextUtil;

import org.quartz.CronExpression;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;

@Service
public class WxTempletService {

    @Resource
    private WxTemplemtMapper wxTemplemtMapper;

    @Autowired
    private QuartzComponent quartzComponent;

    public void operator(WxTemplemt wxTemplemt) {
        if (wxTemplemt.getId() != null) {
            wxTemplemtMapper.updateByPrimaryKey(wxTemplemt);
        } else {
            if (!TextUtil.isEmpty(wxTemplemt.getCron())) {
                try {
                    CronExpression cron = new CronExpression(wxTemplemt.getCron());
                } catch (ParseException e) {
                    throw new BusinessException("cron表达式错误");
                }
                Integer typeCount = wxTemplemtMapper.count(wxTemplemt.getType());
                if (typeCount > 0) {
                    throw new BusinessException("当前类型已存在");
                }
                wxTemplemtMapper.insertSelective(wxTemplemt);
                final HashMap<Object, Object> dataMap = new HashMap<>();
                dataMap.put("id", wxTemplemt.getId());
                dataMap.put("type", "templet_message");
                quartzComponent.getTrigger(TaskQuartzBean.class, wxTemplemt.getCron(), dataMap, wxTemplemt.getType(), wxTemplemt.getType());
            }

        }
    }

    public void operatorTime(WxTemplemt wxTemplemt) {
        final HashMap<Object, Object> dataMap = new HashMap<>();
        dataMap.put("id", wxTemplemt.getId());
        dataMap.put("type", "templet_message");
        quartzComponent.updateJob(TaskQuartzBean.class, wxTemplemt.getType(), wxTemplemt.getType(), wxTemplemt.getCron(), dataMap);
        wxTemplemtMapper.updateByPrimaryKeySelective(wxTemplemt);
    }

    public void removeById(Integer id) {
        final WxTemplemt wxTemplemt = wxTemplemtMapper.selectByPrimaryKey(id);
        wxTemplemtMapper.deleteByPrimaryKey(id);
        quartzComponent.removeJob(wxTemplemt.getType(), wxTemplemt.getType());
    }

    public PageVo<List<WxTemplemt>> getList(String type, Integer page, Integer limit) {
        return new PageVo<List<WxTemplemt>>(wxTemplemtMapper.getList(type, (page - 1) * limit, limit), wxTemplemtMapper.count(type));
    }
}
